package com.letoken.platform.app.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.letoken.platform.app.service.AppVersionInfoService;
import com.letoken.platform.pub.constant.RedisKeyConstant;
import com.letoken.platform.pub.util.BeanUtil;
import com.letoken.platform.repo.app.manager.AppVersionInfoManager;
import com.letoken.platform.repo.app.po.AppVersion;
import com.letoken.platform.repo.app.req.version.AppVersionInfoReq;
import com.letoken.platform.repo.app.res.version.AppVersionInfoRes;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


/**
 * @author : hfanghao
 * @date : 2022-01-18 17:42
 **/
@Service
@Log4j2
public class AppVersionInfoServiceImpl implements AppVersionInfoService {

    @Autowired
    private AppVersionInfoManager appVersionInfoManager;

    @Cacheable(cacheNames = RedisKeyConstant.VERSION_CHECK, key = "'client_' + #req.client  + 'version_' + #req.currentVersion", sync = true)
    @Override
    public AppVersionInfoRes updateCheck(AppVersionInfoReq req) {
        AppVersionInfoRes appVersionInfoRes = new AppVersionInfoRes();
        //获取根据时间倒序第一个版本   也就是最后一个版本
        AppVersion versionInfo = appVersionInfoManager.queryLastVersion(req.getClient());
        if (ObjectUtil.isNull(versionInfo)) {
            return null;
        }
        if (StrUtil.equals(req.getCurrentVersion(), versionInfo.getCurrentVersion())) {
            return null;
        }
        if (!"9.9.9".equals(req.getCurrentVersion())) {
            if (compareVersion(req.getCurrentVersion(), versionInfo.getCurrentVersion())) {
                return null;
            }
        }
        BeanUtil.quickCopy(versionInfo, appVersionInfoRes);
        return appVersionInfoRes;
    }

    /**
     * 需要比较的版本较大，返回正数，否则返回负数，一样返回0
     *
     * @param compareVersion
     * @param currentVersion
     * @return
     */
    private boolean compareVersion(String compareVersion, String currentVersion) {
        String[] compareVersionArray = compareVersion.split("\\.");
        String[] currentVersionArray = currentVersion.split("\\.");
        int idx = 0;
        // 取数组最小长度值
        int minLength = Math.min(compareVersionArray.length, currentVersionArray.length);
        int diff = 0;
        while (idx < minLength && (diff = Integer.parseInt(compareVersionArray[idx]) - Integer.parseInt(currentVersionArray[idx])) == 0) {
            ++idx;
        }
        diff = (diff != 0) ? diff : compareVersionArray.length - currentVersionArray.length;
        return diff > 0;
    }
}
